/**
* @program: src
*
* @description:
*
* @author: Mr.chen
*
* @create: 2020-12-16 14:01
**/
package rpc
import (
	"bytes"
	"ydd-im/service/api/define"
	"ydd-im/service/api/services/wsservice/mapper"
	"ydd-im/service/api/services/wsservice/pb"
	"context"
	"encoding/json"
)
type DBProxyServiceServer struct{}

/**
 * rpc统一数据格式，统一访问路径
 * @access  public
 * @param   pb.ReqExec     req  请求参数
 * @return  pb.RespExec 自定义数据类型
 * @return  error err 错误信息
 */
func (db *DBProxyServiceServer) ExecuteAction(ctx context.Context, req *pb.ReqExec) (res *pb.RespExec,err error) {
	resList := make([]define.ExecResult, len(req.Action))
	// TODO: 检查	req.Sequence req.Transaction两个参数，执行不同的流程
	for idx, singleAction := range req.Action {
		params := []interface{}{}
		dec := json.NewDecoder(bytes.NewReader(singleAction.Params))
		dec.UseNumber()
		// 避免int/int32/int64等自动转换为float64
		//if err := json.Unmarshal(singleAction.Params, &params); err != nil {
		if err := dec.Decode(&params); err != nil {
			resList[idx] = define.ExecResult{
				Suc: false,
				Msg: "请求参数有误",
			}
			continue
		}

		for k, v := range params {
			if _, ok := v.(json.Number); ok {
				params[k], _ = v.(json.Number).Int64()
			}
		}
		// 默认串行执行sql函数
		execRes, err := mapper.FuncCall(singleAction.Name, params...)

		if err != nil {
			resList[idx] = define.ExecResult{
				Suc: false,
				Msg: "函数调用有误",
			}
			continue
		}
		resList[idx] = execRes[0].Interface().(define.ExecResult)

	}
	// TODO: 处理异常
	v,_ :=json.Marshal(resList)
	data :=&pb.RespExec{Data:v}
	return data,nil
}

